/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
//https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=study-plan&id=suan-fa-ru-men&plan=algorithms&plan_progress=1dycqxh

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode* fast = head;
    struct ListNode* slow = head;
    struct ListNode* prev = head;

    if (head == NULL)
    {
        return NULL;
    }

    while (n)
    {
        fast = fast->next;
        --n;
    }

    while (fast)
    {
        fast = fast->next;
        prev = slow;
        slow = slow->next;
    }

    if (slow == head)
    {
        prev = slow->next;
        free(slow);
        slow = NULL;
        return prev;
    }
    else
    {
        prev->next = slow->next;
        free(slow);
        slow = NULL;
        return head;
    }
}